package org.ishequ.weibo.db;

import java.util.ArrayList;
import java.util.List;

import org.ishequ.service.AppWidgetAnimationService;
import org.ishequ.weibo.domain.AppWidgetStatus;

import weibo4android.Status;
import weibo4android.WeiboResponse;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class FriendTimelineDBHelper {
	
	private SQLiteDatabase db;
	private DBOpenHelper openHelper;
	private static FriendTimelineDBHelper dbAdapter = null;


	public static synchronized FriendTimelineDBHelper getInstance(Context context) {
		if (dbAdapter == null)
			dbAdapter = new FriendTimelineDBHelper(context);
		return dbAdapter;
	}
	
	private FriendTimelineDBHelper(Context context) {
		openHelper = new DBOpenHelper(context);
		db = openHelper.getWritableDatabase();
	}

	public void Close() {
		db.close();
		openHelper.close();
	}

	/**
	 * 保存当前用户前20条friendsTimeline
	 * 
	 * @param friendsTimeline
	 */
	public void saveFriendTimeline(List<WeiboResponse> friendsTimeline) {
		db = openHelper.getWritableDatabase();
		db.execSQL("DROP TABLE IF EXISTS " + DBOpenHelper.TB_NAME[1]);
		db.execSQL(DBOpenHelper.TABLE_CREATE_SQL[1]);
		for (int i = 0; i < 20 && i < friendsTimeline.size(); i++) {
			Status status = (Status) friendsTimeline.get(i);
			String id = status.getId() + "";
			String screenName = status.getUser().getScreenName();
			String timelineText = status.getText();

			db.execSQL("insert into " + DBOpenHelper.TB_NAME[1] + " values(?, ?, ?)",
					new String[] { id, screenName, timelineText });
		}
		db.close();
	}

	/**
	 * 获得数据库中所有的friendsTimeline
	 * 
	 * @return
	 */
	public List<AppWidgetStatus> getFriendTimeline() {
		db = openHelper.getReadableDatabase();
		List<AppWidgetStatus> friendTimeline = new ArrayList<AppWidgetStatus>();
		Cursor cursor = db.rawQuery("select * from " + DBOpenHelper.TB_NAME[1],
				new String[] {});
		AppWidgetAnimationService.friendTimelines.clear();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			String id = cursor.getString(0);
			String screenName = cursor.getString(1);
			String timelineText = cursor.getString(2);
			friendTimeline
					.add(new AppWidgetStatus(id, screenName, timelineText));
		}
		cursor.close();
		db.close();
		return friendTimeline;
	}
}
